<?php
/**
 * 2015.9.15 add @@dragon.hu  下载日志
 * 
 * downloadlogdata
 */

defined('BASEPATH') or die('forbidden');

class Downloadlogdata_Controller extends Controller
{
	private $logclass;  //日志分类(账号创建日志，其他日志)
	private $logtype;  //日志类型
	private $viewlist;  //选项类型
	private $urlpath;  //日志源文件地址
	private $zippath;  //存放压缩文件的地址（ftp服务器）
	private $ftppath;  //ftp下载路径
	private $localpath;  //下载日志存放在本地的地址
	private $username;  //ftp服务器账号
	private $passwd;  //ftp服务器密码
	private $ziplist;  //压缩文件列表
	private $deszipfile;  //目标压缩文件
	
	function _init()
	{
		$this->logclass = array('1' => '账号创建日志', '2' => '其他日志');
		$this->logtype = array('1' => '单个日志', '2' => '所有日志');
		$config = get_config();
		//print_r($config['downloadlog']);
		//exit(0);
		//$this->urlpath = "D:/wamp/www/master/duoluotaitanGM/application/log_file/";
		$this->urlpath = $config['downloadlog']['urlpath'];
		//$this->zippath = "D:/wamp/www/master/duoluotaitanGM/application/zip_file/";
		//$this->zippath = "F:/FTPserver/temp/";
		$this->zippath = $config['downloadlog']['zippath'];
		//$this->ftppath = "ftp://127.0.0.1/temp/";
		$this->ftppath = $config['downloadlog']['ftppath'];
		//$this->localpath = "F:/LOGpath/";  不需要了
		//$this->localpath = $config['downloadlog']['localpath'];
		//$this->username = "hutengjiao";  不需要了
		//$this->username = $config['downloadlog']['username'];
		//$this->passwd = "123456";  不需要了
		//$this->passwd = $config['downloadlog']['passwd'];
		
		$permission = $this->auth->role_permission['admin'];
		foreach ($permission as $k => $v)
		{
			if (false !== strpos($k, "log_"))
			{
				foreach ($v as $k1 => $v1)
				{
					if (is_numeric($k1))
						$this->viewlist[$k][$k1] = $v1;
				}
		
			}
		}
		
		if (is_dir($this->zippath))
		{
			$handler = opendir($this->zippath);
			while(($file = readdir($handler)) !== false){
				if ($file != "." && $file != ".."){
					$this->ziplist[] = $file;
				}
			}
 		}
 		
 		//从list中选出一个时间戳最大的，也就是离当前最近的
 		$maxtime = 0;
 		for($i = 1; $i <=count($this->ziplist); $i++)
 		{
 			$file = $this->ziplist [$i - 1];
			$tmparr = explode ( "_", $file );
			$tmptime = $tmparr [count ( $tmparr ) - 2];
			if ($tmptime > $maxtime)
				$maxtime = $tmptime;
 		}
 		//找到目标文件了
 		for ($j = 1; $j <= count($this->ziplist); $j++)
 		{
 		$file = $this->ziplist [$j - 1];
			if (false !== strpos ( $file, $maxtime )) {
				$this->deszipfile = $file;
				break;
			}
 		}
	}
	
	function index()
	{
		if (is_submit())
		{
			$rowdata = $_POST['row'];
			//print_r($rowdata);
			//exit(0);
			//1.先加分区
			$urllist = get_area_list_url();
			$myserver = 0;
			if($rowdata['logclass'] == 2){  //其他日志
			foreach ( $urllist as $k => $v ) {
					if ($v == $rowdata ['area_host']) {
						$myserver = $k;
						break;
					}
				}
				$tmpurl = $this->urlpath . $myserver;
				$admin = $this->auth->fields['username'];
				$lastzippath = $this->zippath.$rowdata['starttime'].'_'.$rowdata['endtime'].'_'.$admin.'_'.time().'_'.$rowdata['logtype'].".zip";
			}else{
				$tmpurl = $this->urlpath."account";
				$admin = $this->auth->fields['username'];
				$lastzippath = $this->zippath.$rowdata['starttime'].'_'.$rowdata['endtime'].'_'.$admin.'_'.time().'_account'.".zip";
			}
			
			
			//2.再按时间搜索
			$path = array();
			for ($i = strtotime($rowdata['starttime']); $i <= strtotime($rowdata['endtime']); $i += 86400)
			{
				$mytmpurl = $tmpurl.'/'.date("Y-n-j", $i);
				if (is_dir($mytmpurl)){
					$path[] = $mytmpurl;
				}
			}
			//3.加入压缩文件
			//$this->add_file_to_zip($path, '/', $lastzippath, $rowdata['permission'], $rowdata['logtype'], $rowdata['logclass']);
			$this->add_fileto_zip($path, $lastzippath, $rowdata['permission'], $rowdata['logtype'], $rowdata['logclass']);
// 			if (is_dir($this->zippath))
// 			{
// 				$handler = opendir($this->zippath);
// 				while(($file = readdir($handler)) !== false){
// 					if ($file != "." && $file != ".."){
// 						$this->ziplist[] = $file;
// 					}
// 				}
// 			}
// 			$this->view->assign("ziplist", $this->ziplist);
		}
		$this->view->assign("arealist", $this->form->select("row[area_host]", get_area_list_host(), '', array('id' => 'area_host')));
		//$this->view->assign("logtype", $this->form->select("row[log_type]", $this->logtype, '', array('id' => 'log_type')));
		$this->view->assign("logclass", $this->logclass);
		$this->view->assign("logtype", $this->logtype);
		$this->view->display("download_log/downloadlogdata/index");
	}
	
	/*function add_file_tozip($path, $zip_file, $selectedfile, $logtype, $logclass)
	{
		$zip = new ZipArchive();
		$res = $zip->open($zip_file, ZIPARCHIVE::OVERWRITE);
		if ($res === true){
			//账号的情况
			if ($logclass == 1)
			{
				if (is_dir($path[0]))  //选择一个文件夹，遍历所有文件来创建
					$handler = opendir($path[0]);
					while(($file = readdir($handler)) !== false)
					{
						$tmpfile = iconv("gbk", "UTF-8", $file);
						//1.取出文件的描述名
						$filenamearr = explode('-', $tmpfile);
						$filename = substr($filenamearr[0], 0, -4);
						//2.在一个临时的文件夹中创建这些文件
						
					}
					//3.把所有文件依文件名写入这些创建的文件中
					
					//4.再把整个临时文件夹压缩，删除此临时文件夹
					
			}else{
				//一般日志的情况
					
				//所有日志的情况
				
			}
		}
	}*/
	
	function add_fileto_zip($path, $zip_file, $selectedfile, $logtype, $logclass)
	{
// 		print_r($path);
// 		echo "<br>++++<br>";
// 		print_r($zip_file);
// 		echo "<br>++++<br>";
// 		print_r($selectedfile);
// 		echo "<br>++++<br>";
// 		print_r($logtype);
// 		echo "<br>++++<br>";
// 		print_r($logclass);
// 		exit(0);
		
		$zip = new ZipArchive();
		$res = $zip->open($zip_file, ZIPARCHIVE::OVERWRITE);
		if($res === TRUE)
		{
			//1.先将path[0]下文件加入指定文件目录
			//$tmpallfileinzip = array();
			if (!is_dir($this->zippath."tempzip")){
				mkdir($this->zippath."tempzip");
			}
			//exit();
			if (is_dir($path[0])){
				$handler = opendir($path[0]);
				while (($file = readdir($handler)) !== false){
					if ($file == '.' || $file == '..') continue;
					$tmpfile = iconv("gbk", "UTF-8", $file);
					if ($logtype == 1 && $logclass == 2){
						for($j = 0; $j < count ( $selectedfile ); $j ++) {
							$tmpfilestr = substr ( $selectedfile [$j], 0, - 3 ); // 去掉字符串中的'log',然后看是否包含在目标字符串中
							if (false !== strpos ( $tmpfile, $tmpfilestr )) {
								//改一下存入文件名,存入临时文件夹
								$filenamearr = explode('-', $file);
								$filename = substr($filenamearr[0], 0, -4);
								//$zip->addFile($path[0]."/".$filename.'.txt', $filename.'.txt');
								file_put_contents($this->zippath."tempzip/".$filename.'.txt', file_get_contents($path[0]."/".$file));
								//$tmpallfileinzip[] = $filename.'.txt';
							}
						}
					}else{
						//改一下存入文件名
						$filenamearr = explode('-', $file);
						$filename = substr($filenamearr[0], 0, -4);
						//$zip->addFile ( $path[0] . "/" . $file.'.txt', $filename.'.txt');
						file_put_contents($this->zippath."tempzip/".$filename.'.txt', file_get_contents($path[0].'/'.$file));
						//$tmpallfileinzip[] = $filename.'.txt';
					}
				}
				closedir($handler);
			}
			//print_r($tmpallfileinzip);
			//exit(0);
			//2.再将其他path下对应的文件读取字符串加入到相应文件的目录中
			for ($i = 1; $i < count($path); $i++){
				if (is_dir($path[$i])){
					$handler = opendir($path[$i]);
					while (($file = readdir($handler)) !== false){
						$tmpfile = iconv("gbk", "UTF-8", $file);
						//如果文件名中的汉字同名,则加入此文件中
						//先读取此文件中的内容
						$filenamearr = explode('-', $file);
						$filename = substr($filenamearr[0], 0, -4);
						//文件是否存在
						if (file_exists($this->zippath."tempzip/".$filename.'.txt')){
							file_put_contents($this->zippath.'tempzip/'.$filename.'.txt', file_get_contents($path[$i].'/'.$file), FILE_APPEND);
							//$zip->addFromString("$filename.'.txt'", file_get_contents("path[$i].'/'.$file"));
						}
					}
					closedir ($handler);
				}
			}
			//exit(0);
			//////把临时文件的内容压缩
			if (is_dir($this->zippath."tempzip")) {
				$handler = opendir($this->zippath."tempzip");
				while (($file = readdir($handler)) !== false){
					if ($file == '.' || $file == '..') continue;
					//print_r($this->zippath."tempzip/".$file);
					$zip->addFile($this->zippath."tempzip/".$file, /*"targetfiles/".*/$file);
				}
				closedir($handler);
			}
			//exit(0);
			$zip->close();
			//////删除临时文件夹和文件
			if($handle = opendir($this->zippath . "tempzip")){
			while (false !== ($item = readdir($handle))){
				if ($item != "." && $item != "..") {
					unlink($this->zippath . "tempzip/" . $item);
				}
			}
				closedir($handle);
				rmdir($this->zippath."tempzip");
			}
		}else
		{
			echo 'failed, code:' . $res;
		}
	}
	
	function add_file_to_zip($path, $base_path, $zip_file, $selectedfile, $logtype, $logclass)
	{
		$zip = new ZipArchive(); //首先实例化这个类
		$res = $zip->open($zip_file, ZIPARCHIVE::OVERWRITE);
		if ($res === TRUE)
		{
			for ($i = 0; $i < count($path); $i++)
			{
				if (is_dir ( $path[$i] )) {
					$handler = opendir ( $path[$i] );
					while ( ($file = readdir ( $handler )) !== false ) {
						$tmpfile = iconv("gbk","UTF-8", $file);  //编码啊，坑死了！！！
						if ($file != "." && $file != "..") {
							if (is_dir ( $path[$i] . "/" . $file )) {
								$this->add_file_to_zip ( $path[$i] . "/" . $file, $zip, $base_path );
							} else {
								// / 通过 $base_path 分割 $path[$i]，保存成数组
								$dir_path = explode ( $base_path, $path[$i] );
								// /print_r($dir_path);
								if (is_array ( $dir_path )) {
									$arr_size = sizeof ( $dir_path );
									$flag = 0;
									if ($logclass == 1){
										$flag = 1;
									}else{
										for($j = 0; $j < count ( $selectedfile ); $j ++) {
											$tmpfilestr = substr ( $selectedfile [$j], 0, - 3 ); // 去掉字符串中的'log',然后看是否包含在目标字符串中
											if (false !== strpos ( $tmpfile, $tmpfilestr )) {
												$flag = 1;
												break;
											}
										}
									}
									if ($flag == 1 || $logtype == 2) {
										$zip->addFile ( $path[$i] . "/" . $file, /*$dir_path [$arr_size - 1] . '/' .*/ $file );
									}
								}
							}
						}
					}
					closedir ( $handler );
				} 
// 				else {
// 					echo "文件夹不存在";
// 				}
			}
			$zip->close();
		}
		else
		{
			echo 'failed, code:' . $res;
		}
	}
	
	function flexigrid() {
		list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();

		/*if($this->deszipfile != false)
		{
			$value['id'] = 1;
			$value['filename'] = $this->deszipfile;
			$rows[] = array('id' => 1, 'cell' => $value);
		}*/
		
		for($i = 1; $i <=count($this->ziplist); $i++)
		{
			$file = $this->ziplist [$i - 1];
			$tmparr = explode ( "_", $file );
			$tmptime = $tmparr [count ( $tmparr ) - 2];
			$value['id'] = $i;
			$value['filename'] = $file;
			$value['createtime'] = date("Y-m-d H:i:s", $tmptime);
			$rows[] = array('id' => $i, 'cell' => $value);
		}
		$total = count($rows);
		$result = array(
				'page' => $page,
				'total' => $total,
				'rows' => $rows
		);
		echo json_encode($result);
	}
	
	function edit($id=0)
	{
		/*if (is_submit())
		{
			//下载
			$downloadfilename = $this->deszipfile;
// 			print_r($this->ftppath);
// 			echo "<br>++++<br>";
// 			print_r($this->localpath);
// 			echo "<br>++++<br>";
// 			print_r($downloadfilename);
// 			echo "<br>++++<br>";
// 			exit(0);
			$this->download_file($this->ftppath.'/'.$downloadfilename, $this->localpath, $downloadfilename);
			cp_tips("success");
		}*/
		$this->view->assign("logtype", $this->logtype);
		//$this->view->assign("selectedzip", $this->ziplist[$id - 1]);
		//$row['zipfilename'] = $this->deszipfile;
		$row['zipfilename'] = $this->ziplist[$id - 1];
		$row['ftppath'] = $this->ftppath;
		$this->view->display("download_log/downloadlogdata/edit", array('row' => $row));
	}
	
	/*
	function download_file($url, $filepath, $filename)
	{
		$curl = curl_init();
		$target_ftp_file = $url;//完整路径
	
		curl_setopt($curl, CURLOPT_URL,$target_ftp_file);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_VERBOSE, 1);
		curl_setopt($curl, CURLOPT_FTP_USE_EPSV, 0);
		curl_setopt($curl, CURLOPT_TIMEOUT, 300); // times out after 300s
		curl_setopt($curl, CURLOPT_USERPWD, "$this->username".":"."$this->passwd");//FTP用户名：密码
		// Sets up the output file
	
		$target_path = $filepath;
		if(false == is_dir($target_path))
		{
			mkdir($target_path);
		}
		$target_path = $target_path .'/'. $filename;
		$outfile = fopen($target_path, 'wb');//保存到本地的文件名
		curl_setopt($curl, CURLOPT_FILE, $outfile);
	
		// Executes the cURL
		$info = curl_exec($curl);
		fclose($outfile);
		$error_no = curl_errno($curl);
		curl_close($curl);
	}*/
}